package com.seqb.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author lilinshen
 * @title 反射工具类
 * @description 请填写相关描述
 * @date 2019/11/20
 */
public class ReflectUtils {

    /**
     * 构造方法私有
     */
    private ReflectUtils() {
    }

    /**
     * 根据字段名称获取对象的属性
     */
    public static Object getFieldValueByName(String fieldName, Object target) throws Exception {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = target.getClass().getMethod(getter, new Class[]{});
            return method.invoke(target, new Object[]{});
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取所有字段名字
     */
    public static String[] getFiledName(Object target) throws Exception {
        Field[] fields = target.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; ++i) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    /**
     * 获取所有属性的值
     */
    public static Object[] getFiledValues(Object target) throws Exception {
        String[] fieldNames = getFiledName(target);
        Object[] value = new Object[fieldNames.length];
        for (int i = 0; i < fieldNames.length; ++i) {
            value[i] = getFieldValueByName(fieldNames[i], target);
        }
        return value;
    }

}
